//
//  ViewController.swift
//  锄大地计分器
//
//  Created by Chen on 2017/7/3.
//  Copyright © 2017年 Chen. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITableViewDelegate, UITableViewDataSource {
    
    //界面元素
    @IBOutlet var p1: UIButton!
    @IBOutlet var p2: UIButton!
    @IBOutlet var p3: UIButton!
    @IBOutlet var p4: UIButton!
    @IBOutlet var m1: UILabel!
    @IBOutlet var m2: UILabel!
    @IBOutlet var m3: UILabel!
    @IBOutlet var m4: UILabel!
    @IBOutlet var tableview: UITableView!
    @IBOutlet var leftbtn: UIBarButtonItem!
    @IBOutlet var rightbtn: UIBarButtonItem!
    @IBOutlet var navigation: UINavigationBar!
    var picker = UIPickerView()
    var btable = UITableView()
    
    var type = 1
    var i = 0
    
    //适配长度
    var width = 0
    var height = 0
    
    
    //玩家名保存路径
    var docpath = ""
    
    //玩家分数
    var mon:Double = 0.01
    //每一局玩家剩下的牌
    var cp1 = 0
    var cp2 = 0
    var cp3 = 0
    var cp4 = 0
    //每个玩家分数统计
    var po1 = 0
    var po2 = 0
    var po3 = 0
    var po4 = 0
    //每个玩家总共剩下的牌
    var c1 = 0
    var c2 = 0
    var c3 = 0
    var c4 = 0
    //每个玩家和其他玩家的分差
    var di1 = 0
    var di2 = 0
    var di3 = 0
    var di4 = 0
    //新游戏菜单按钮
    var b1 = UIButton()
    var b2 = UIButton()
    var b3 = UIButton()
    var b4 = UIButton()
    //黑桃2计数器
    var f1 = [Bool]()
    var f2 = [Bool]()
    var f3 = [Bool]()
    var f4 = [Bool]()
    //分数记录
    var rec = [[Int]]()
    var cancel = UIAlertAction(title: "好", style: .cancel, handler: nil)
    var cells = [UITableViewCell]()
    var bcells = [UITableViewCell]()
    var bbtns = [UIButton]()
    

    override func viewDidLoad() {

        // Do any additional setup after loading the view, typically from a nib.
        docpath = NSHomeDirectory() + "/Documents/player.txt"
        width = Int(UIScreen.main.bounds.width)
        height = Int(UIScreen.main.bounds.height)
        
        
        //navigation.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 200)
        let statusBarWindow : UIView = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView
        let statusBar : UIView = statusBarWindow.value(forKey: "statusBar") as! UIView
        if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
            statusBar.backgroundColor = #colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1)
        }
        
        navigation.isUserInteractionEnabled = true
        rightbtn.action = #selector(resetbutton)
        leftbtn.action = #selector(balance)
        
        tableview.delegate = self
        tableview.dataSource = self
        tableview.allowsSelection = true
        tableview.isUserInteractionEnabled = true
        tableview.tableFooterView = UIView()
        tableview.separatorInset = UIEdgeInsets.zero
        tableview.showsVerticalScrollIndicator = false
        tableview.tableFooterView = UIView()
        tableview.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: CGFloat(height / 2), right: 0)
        tableview.frame = CGRect(x: 15, y: 103, width: width - 30, height: height - 141)
        
        
        
        p1.titleLabel?.lineBreakMode = .byClipping
        p2.titleLabel?.lineBreakMode = .byClipping
        p3.titleLabel?.lineBreakMode = .byClipping
        p4.titleLabel?.lineBreakMode = .byClipping
        p1.frame = CGRect(x: 15, y: 68, width: (width - 30) / 4, height: 30)
        p2.frame = CGRect(x: 15 + (width - 30) / 4, y: 68, width: (width - 30) / 4, height: 30)
        p3.frame = CGRect(x: 15 + (width - 30) / 2, y: 68, width: (width - 30) / 4, height: 30)
        p4.frame = CGRect(x: 16 + 3 * (width - 30) / 4, y: 68, width: (width - 30) / 4, height: 30)
        p1.titleLabel?.textAlignment = .center
        p2.titleLabel?.textAlignment = .center
        p3.titleLabel?.textAlignment = .center
        p4.titleLabel?.textAlignment = .center
        p1.addTarget(self, action: #selector(name(button:)), for: .touchUpInside)
        p2.addTarget(self, action: #selector(name(button:)), for: .touchUpInside)
        p3.addTarget(self, action: #selector(name(button:)), for: .touchUpInside)
        p4.addTarget(self, action: #selector(name(button:)), for: .touchUpInside)
        let tap1 = UITapGestureRecognizer(target: self, action: #selector(taplabel))
        let tap2 = UITapGestureRecognizer(target: self, action: #selector(taplabel))
        let tap3 = UITapGestureRecognizer(target: self, action: #selector(taplabel))
        let tap4 = UITapGestureRecognizer(target: self, action: #selector(taplabel))
        m1.isUserInteractionEnabled = true
        m2.isUserInteractionEnabled = true
        m3.isUserInteractionEnabled = true
        m4.isUserInteractionEnabled = true
        m1.frame = CGRect(x: 0, y: height - 38, width: self.width / 4, height: 38)
        m2.frame = CGRect(x: self.width / 4, y: height - 38, width: self.width / 4 + 1, height: 38)
        m3.frame = CGRect(x: self.width / 2, y: height - 38, width: self.width / 4 + 1, height: 38)
        m4.frame = CGRect(x: 3 * self.width / 4, y: height - 38, width: self.width / 4 + 1, height: 38)
        m1.addGestureRecognizer(tap1)
        m2.addGestureRecognizer(tap2)
        m3.addGestureRecognizer(tap3)
        m4.addGestureRecognizer(tap4)
        m1.lineBreakMode = .byClipping
        m2.lineBreakMode = .byClipping
        m3.lineBreakMode = .byClipping
        m4.lineBreakMode = .byClipping
        
        b1.addTarget(self, action: #selector(spade(button:)), for: .touchUpInside)
        b2.addTarget(self, action: #selector(spade(button:)), for: .touchUpInside)
        b3.addTarget(self, action: #selector(spade(button:)), for: .touchUpInside)
        b4.addTarget(self, action: #selector(spade(button:)), for: .touchUpInside)
        b1.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
        b2.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
        b3.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
        b4.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
        b1.frame = CGRect(x: 0, y: 50, width: 80, height: 30)
        b2.frame = CGRect(x: 65, y: 50, width: 80, height: 30)
        b3.frame = CGRect(x: 130, y: 50, width: 80, height: 30)
        b4.frame = CGRect(x: 195, y: 50, width: 80, height: 30)
        
        
        //结算时的选钱按钮初始化
        for num in (0...8){
            bbtns.append(UIButton(type: .roundedRect))
            if(num % 3 == 0){
                bbtns[num].setTitle(NSString(format: "%.2f", pow(10.0, -Double(2 - num / 3))) as String, for: .normal)
            }
            else if(num % 3 == 1){
                bbtns[num].setTitle(NSString(format: "%.2f", 2 * pow(10.0, -Double(2 - num / 3))) as String, for: .normal)
            }
            else if(num % 3 == 2){
                bbtns[num].setTitle(NSString(format: "%.2f", 5 * pow(10.0, -Double(2 - num / 3))) as String, for: .normal)
            }
            bbtns[num].frame = CGRect(x: 10 * (num % 3 + 1) + 77 * (num % 3), y: 0, width: 77, height: 26)
            bbtns[num].setTitleColor(#colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1), for: .normal)
            bbtns[num].addTarget(self, action: #selector(bmon(button:)), for: .touchUpInside)
            bbtns[num].layer.borderColor = #colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1).cgColor
            bbtns[num].layer.borderWidth = 2
            bbtns[num].layer.cornerRadius = 6
        }
        bbtns[0].setTitleColor(#colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1), for: .normal)
        bbtns[0].layer.borderColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1).cgColor
    }
    
    //结算按钮
    func balance(){
        let balance = UIAlertController(title: "结算\n\n\n\n\n\n\n\n\n", message: "", preferredStyle: .alert)
        btableinit()
        btable = UITableView(frame: CGRect(x: 0, y: 50, width: 270, height: 210), style: .plain)
        btable.allowsSelection = false
        btable.tableFooterView = UIView()
        btable.backgroundColor = balance.view.backgroundColor
        btable.separatorColor = UIColor.clear
        btable.separatorInset = UIEdgeInsets.zero
        btable.isScrollEnabled = false
        btable.delegate = self
        btable.dataSource = self
        balance.view.addSubview(btable)
        
        let cancel = UIAlertAction(title: "关闭", style: .cancel, handler: nil)
        balance.addAction(cancel)
        
        self.present(balance, animated: true, completion: nil)
    }
    
    //balance界面按钮点击事件
    func bmon(button: UIButton){
        button.setTitleColor(#colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1), for: .normal)
        button.layer.borderColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1).cgColor
        for num in 0...bbtns.count - 1{
            if(bbtns[num].currentTitleColor != #colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1) && bbtns[num] != button){
                bbtns[num].setTitleColor(#colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1), for: .normal)
                bbtns[num].layer.borderColor = #colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1).cgColor
            }
        }
        mon = (button.currentTitle! as NSString).doubleValue
        btableinit()
        btable.reloadData()
        writetolabel()
    }
    
    //balance界面tableview数据
    func btableinit(){
        //创建balance界面的tableviewcells
        //第一行:玩家名字
        bcells.removeAll()
        let cell1 = UITableViewCell(frame: CGRect(x: 0, y: 0, width: 270, height: 30))
        cell1.backgroundColor = UIColor.clear
        let p11 = UILabel(frame: CGRect(x: 0, y: 0, width: 67.5, height: 30))
        let p12 = UILabel(frame: CGRect(x: 67.5, y: 0, width: 67.5, height: 30))
        let p13 = UILabel(frame: CGRect(x: 135, y: 0, width: 67.5, height: 30))
        let p14 = UILabel(frame: CGRect(x: 202.5, y: 0, width: 67.5, height: 30))
        p11.lineBreakMode = .byTruncatingMiddle
        p12.lineBreakMode = .byTruncatingMiddle
        p13.lineBreakMode = .byTruncatingMiddle
        p14.lineBreakMode = .byCharWrapping
        p11.text = p1.currentTitle
        p12.text = p2.currentTitle
        p13.text = p3.currentTitle
        p14.text = p4.currentTitle
        p11.textAlignment = .center
        p12.textAlignment = .center
        p13.textAlignment = .center
        p14.textAlignment = .center
        p11.textColor = #colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1)
        p12.textColor = #colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1)
        p13.textColor = #colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1)
        p14.textColor = #colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1)
        cell1.addSubview(p11)
        cell1.addSubview(p12)
        cell1.addSubview(p13)
        cell1.addSubview(p14)
        bcells.append(cell1)
        //第二行:玩家分数
        let cell2 = UITableViewCell(frame: CGRect(x: 0, y: 0, width: 270, height: 30))
        cell2.backgroundColor = #colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1)
        let p21 = UILabel(frame: CGRect(x: 0, y: 0, width: 67.5, height: 30))
        let p22 = UILabel(frame: CGRect(x: 67.5, y: 0, width: 67.5, height: 30))
        let p23 = UILabel(frame: CGRect(x: 135, y: 0, width: 67.5, height: 30))
        let p24 = UILabel(frame: CGRect(x: 202.5, y: 0, width: 67.5, height: 30))
        p21.text = String(po1)
        p22.text = String(po2)
        p23.text = String(po3)
        p24.text = String(po4)
        p21.textAlignment = .center
        p22.textAlignment = .center
        p23.textAlignment = .center
        p24.textAlignment = .center
        p21.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        p22.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        p23.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        p24.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        cell2.addSubview(p21)
        cell2.addSubview(p22)
        cell2.addSubview(p23)
        cell2.addSubview(p24)
        bcells.append(cell2)
        //第三行:玩家资产
        let cell3 = UITableViewCell(frame: CGRect(x: 0, y: 0, width: 270, height: 30))
        cell3.backgroundColor = #colorLiteral(red: 0.2891559601, green: 0.7254244685, blue: 0.9668720365, alpha: 1)
        let p31 = UILabel(frame: CGRect(x: 0, y: 0, width: 67.5, height: 30))
        let p32 = UILabel(frame: CGRect(x: 67.5, y: 0, width: 67.5, height: 30))
        let p33 = UILabel(frame: CGRect(x: 135, y: 0, width: 67.5, height: 30))
        let p34 = UILabel(frame: CGRect(x: 202.5, y: 0, width: 67.5, height: 30))
        p31.font = UIFont.systemFont(ofSize: 15)
        p32.font = UIFont.systemFont(ofSize: 15)
        p33.font = UIFont.systemFont(ofSize: 15)
        p34.font = UIFont.systemFont(ofSize: 15)
        p31.text = NSString(format: "￥%.2f", Double(di1) * mon) as String
        p32.text = NSString(format: "￥%.2f", Double(di2) * mon) as String
        p33.text = NSString(format: "￥%.2f", Double(di3) * mon) as String
        p34.text = NSString(format: "￥%.2f", Double(di4) * mon) as String
        p31.textAlignment = .center
        p32.textAlignment = .center
        p33.textAlignment = .center
        p34.textAlignment = .center
        p31.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        p32.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        p33.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        p34.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        cell3.addSubview(p31)
        cell3.addSubview(p32)
        cell3.addSubview(p33)
        cell3.addSubview(p34)
        bcells.append(cell3)
    }
    
    //选择玩家名界面
    func name(button: UIButton){
        let sheet = UIAlertController(title: "选择玩家名", message: "", preferredStyle: .actionSheet)
        let file = FileManager.default
        
        //取消按钮
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        sheet.addAction(cancel)
        
        //新玩家按钮
        let new = UIAlertAction(title: "新玩家..", style: .default) { (action: UIAlertAction) in
            self.newp(button: button)
        }
        sheet.addAction(new)
        
        //读取文件获得玩家名
        if(file.fileExists(atPath: docpath)){
            let read = NSData(contentsOfFile: docpath)
            let ps = NSString(data: read! as Data, encoding: String.Encoding.utf8.rawValue)
            let players = ps?.components(separatedBy: "\n")
            for i in 0...4{
                if(players?[i] != ""){
                    let pc = UIAlertAction(title: players?[i], style: .default, handler: {  (action: UIAlertAction) in
                        button.setTitle(players?[i], for: .normal)
                    })
                    sheet.addAction(pc)
                }
                else{
                    break
                }
            }
        }
        
        //清除按钮
        let del = UIAlertAction(title: "清除记录..", style: .default) { (action: UIAlertAction) in
            if(file.fileExists(atPath: self.docpath)){
                try!file.removeItem(atPath: self.docpath)
            }
        }
        sheet.addAction(del)
        
        self.present(sheet, animated: true, completion: nil)
    }
    
    //新玩家按钮
    func newp(button: UIButton){
        let alert = UIAlertController(title: "新玩家", message: "", preferredStyle: .alert)
        var player = ""
        //let textf = UITextField()
        alert.addTextField { (field: UITextField) in
        }
        let ok = UIAlertAction(title: "确定", style: .default) { (action: UIAlertAction!) in
            player = (alert.textFields?.last?.text!)!
            if(player != ""){
                player += "\n"
                let filem = FileManager.default
                if(!filem.fileExists(atPath: self.docpath)){
                    try!player.write(toFile: self.docpath, atomically: true, encoding: String.Encoding.utf8)
                }
                else{
                    self.writetofile(content: player as NSString)
                }
                button.setTitle(player, for: .normal)
            }
            else{
                let empty = UIAlertController(title: "错误", message: "玩家名不能为空！", preferredStyle: .alert)
                empty.addAction(self.cancel)
                self.present(empty, animated: true, completion: nil)
            }
        }
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alert.addAction(ok)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
    
    //输出玩家名到文件
    func writetofile(content: NSString){
        let data = NSMutableData()
        data.append(content.utf8String!, length: content.length)
        let read = NSData(contentsOfFile: docpath)
        data.append(read! as Data)
        try!data.write(toFile: docpath, options: .atomic)
    }
    
    //点击分数栏改变分数显示方式
    func taplabel(){
        if(type < 4){
            self.type += 1
        }
        else{
            type = 1
        }
        writetolabel()
    }
    
    //将分数写入Label
    func writetolabel(){
        if(self.type != 3){
            m1.font = UIFont.systemFont(ofSize: 23)
            m2.font = UIFont.systemFont(ofSize: 23)
            m3.font = UIFont.systemFont(ofSize: 23)
            m4.font = UIFont.systemFont(ofSize: 23)
        }
        if(self.type == 1){
            self.di1 = (self.po2 - self.po1) + (self.po3 - self.po1) + (self.po4 - self.po1)
            self.di2 = (self.po1 - self.po2) + (self.po3 - self.po2) + (self.po4 - self.po2)
            self.di3 = (self.po1 - self.po3) + (self.po2 - self.po3) + (self.po4 - self.po3)
            self.di4 = (self.po1 - self.po4) + (self.po2 - self.po4) + (self.po3 - self.po4)
            m1.text = String(di1)
            m2.text = String(di2)
            m3.text = String(di3)
            m4.text = String(di4)
        }
        else if(self.type == 2){
            m1.text = String(po1)
            m2.text = String(po2)
            m3.text = String(po3)
            m4.text = String(po4)
        }
        else if(self.type == 3){
            self.di1 = (self.po2 - self.po1) + (self.po3 - self.po1) + (self.po4 - self.po1)
            self.di2 = (self.po1 - self.po2) + (self.po3 - self.po2) + (self.po4 - self.po2)
            self.di3 = (self.po1 - self.po3) + (self.po2 - self.po3) + (self.po4 - self.po3)
            self.di4 = (self.po1 - self.po4) + (self.po2 - self.po4) + (self.po3 - self.po4)
            m1.text = ("￥" + (NSString(format: "%.2f", mon * Double(di1)) as String))
            m1.font = UIFont.systemFont(ofSize: 17)
            m2.text = ("￥" + (NSString(format: "%.2f", mon * Double(di2)) as String))
            m2.font = UIFont.systemFont(ofSize: 17)
            m3.text = ("￥" + (NSString(format: "%.2f", mon * Double(di3)) as String))
            m3.font = UIFont.systemFont(ofSize: 17)
            m4.text = ("￥" + (NSString(format: "%.2f", mon * Double(di4)) as String))
            m4.font = UIFont.systemFont(ofSize: 17)
        }
        else if(self.type == 4){
            m1.text = String(c1)
            m2.text = String(c2)
            m3.text = String(c3)
            m4.text = String(c4)
        }
    }
    
    //新游戏按钮
    func newgame(path: IndexPath){
        let game = UIAlertController(title:"\n\n\n\n\n\n\n\n\n", message: "", preferredStyle: .alert)
        if(path.row == i){
            game.title = "新游戏\n\n\n\n\n\n\n\n\n"
            self.f1[path.row] = false
            self.f2[path.row] = false
            self.f3[path.row] = false
            self.f4[path.row] = false
        }
        else{
            game.title = "选分\n\n\n\n\n\n\n\n\n"
        }
        picker = UIPickerView(frame: CGRect(x: 0, y: 65, width: 270, height: 150))
        picker.dataSource = self
        picker.delegate = self
        game.view.addSubview(picker)
        
        //找个好位置
        var rc1 = 0
        var rc2 = 0
        var rc3 = 0
        var rc4 = 0
        
        var rpo1 = 0
        var rpo2 = 0
        var rpo3 = 0
        var rpo4 = 0
        
        if(path.row != self.i){
            let rc1 = rec[path.row][0]
            let rc2 = rec[path.row][1]
            let rc3 = rec[path.row][2]
            let rc4 = rec[path.row][3]
            
            let rpo1 = point(c: rec[path.row][0], num: 1, r: path.row)
            let rpo2 = point(c: rec[path.row][1], num: 2, r: path.row)
            let rpo3 = point(c: rec[path.row][2], num: 3, r: path.row)
            let rpo4 = point(c: rec[path.row][3], num: 4, r: path.row)
        
            f1[path.row] = false
            f2[path.row] = false
            f3[path.row] = false
            f4[path.row] = false
            
        }
        
        
        //初始化按钮新游戏界面按钮
        b1.setTitle(self.p1.currentTitle, for: .normal)
        b2.setTitle(self.p2.currentTitle, for: .normal)
        b3.setTitle(self.p3.currentTitle, for: .normal)
        b4.setTitle(self.p4.currentTitle, for: .normal)
        b1.tag = path.row
        b2.tag = path.row
        b3.tag = path.row
        b4.tag = path.row
        game.view.addSubview(b1)
        game.view.addSubview(b2)
        game.view.addSubview(b3)
        game.view.addSubview(b4)
        //界面的两个按钮
        let ok = UIAlertAction(title: "确定", style: .default) { (UIAlertAction) in
            if(path.row != self.i){
                self.c1 -= rc1
                self.c2 -= rc2
                self.c3 -= rc3
                self.c4 -= rc4
                
                self.po1 -= rpo1
                self.po2 -= rpo2
                self.po3 -= rpo3
                self.po4 -= rpo4
            }
            
            
            self.cp1 = self.picker.selectedRow(inComponent: 0)
            self.cp2 = self.picker.selectedRow(inComponent: 1)
            self.cp3 = self.picker.selectedRow(inComponent: 2)
            self.cp4 = self.picker.selectedRow(inComponent: 3)
            
            let buf = [self.cp1,self.cp2,self.cp3,self.cp4]
            if(path.row == self.i){
                self.rec.append(buf)
            }
            else{
                self.rec[path.row] = buf
            }
            
            var count = 0
            if(self.cp1 == 0){
                count += 1
            }
            if(self.cp2 == 0){
                count += 1
            }
            if(self.cp3 == 0){
                count += 1
            }
            if(self.cp4 == 0){
                count += 1
            }
            
            if(count > 1){
                let dwin = UIAlertController(title: "一局不能有两个赢家", message: "", preferredStyle: .alert)
                dwin.addAction(self.cancel)
                self.present(dwin, animated: true, completion: nil)
                self.present(game, animated: true, completion: nil)
                return
            }
            
            self.po1 += self.point(c: self.cp1, num: 1, r: path.row)
            self.po2 += self.point(c: self.cp2, num: 2, r: path.row)
            self.po3 += self.point(c: self.cp3, num: 3, r: path.row)
            self.po4 += self.point(c: self.cp4, num: 4, r: path.row)
            
            
            self.c1 += self.cp1
            self.c2 += self.cp2
            self.c3 += self.cp3
            self.c4 += self.cp4
            
            self.writetolabel()
            
            self.addrow(path: path)
        }
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        game.addAction(cancel)
        game.addAction(ok)
        
        self.present(game, animated: true, completion: nil)
    }
    
    //判断黑桃2
    func spade(button: UIButton){
        if(button == b1){
            if(!f1[button.tag]){
                f1[b1.tag] = true
                b1.setTitleColor(#colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1), for: .normal)
                f2[b2.tag] = false
                b2.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f3[b3.tag] = false
                b3.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f4[b4.tag] = false
                b4.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
            }
            else{
                button.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f1[b1.tag] = false
            }
        }
        else if(button == b2){
            if(!f2[button.tag]){
                f2[b2.tag] = true
                button.setTitleColor(#colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1), for: .normal)
                f1[b1.tag] = false
                b1.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f3[b3.tag] = false
                b3.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f4[b4.tag] = false
                b4.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
            }
            else{
                button.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f2[b2.tag] = false
            }
        }
        else if(button == b3){
            if(!f3[button.tag]){
                f3[b3.tag] = true
                button.setTitleColor(#colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1), for: .normal)
                f1[b1.tag] = false
                b1.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f2[b2.tag] = false
                b2.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f4[b4.tag] = false
                b4.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
            }
            else{
                button.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f3[b3.tag] = false
            }
        }
        else if(button == b4){
            if(!f4[button.tag]){
                f4[b4.tag] = true
                button.setTitleColor(#colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1), for: .normal)
                f1[b1.tag] = false
                b1.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f2[b2.tag] = false
                b2.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f3[b3.tag] = false
                b3.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
            }
            else{
                button.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
                f4[b4.tag] = false
            }
        }
    }
    
    //换算分
    func point(c: Int, num: Int, r: Int) -> Int{
        var point = 0
        if(c == 13){
            point = c * 4
        }
        else if(c >= 10 && c <= 12){
            point = c * 3
        }
        else if(c >= 8 && c <= 9){
            point = c * 2
        }
        else{
            point = c
        }
        if(num == 1 && f1[r]){
            point *= 2
        }
        else if(num == 2 && f2[r]){
            point *= 2
        }
        else if(num == 3 && f3[r]){
            point *= 2
        }
        else if(num == 4 && f4[r]){
            point *= 2
        }
        return point
    }
    
    //增加一行分数
    func addrow(path: IndexPath){
        let mark1 = UILabel(frame: CGRect(x: 0, y: 0, width: (width - 30) / 4, height: 40))
        let mark2 = UILabel(frame: CGRect(x: (width - 30) / 4, y: 0, width: (width - 30) / 4, height: 40))
        let mark3 = UILabel(frame: CGRect(x: (width - 30) / 2, y: 0, width: (width - 30) / 4, height: 40))
        let mark4 = UILabel(frame: CGRect(x: 3 * (width - 30) / 4, y: 0, width: (width - 30) / 4, height: 40))
        mark1.textAlignment = .center
        mark2.textAlignment = .center
        mark3.textAlignment = .center
        mark4.textAlignment = .center
        mark1.font = UIFont.systemFont(ofSize: 21)
        mark2.font = UIFont.systemFont(ofSize: 21)
        mark3.font = UIFont.systemFont(ofSize: 21)
        mark4.font = UIFont.systemFont(ofSize: 21)
        let cell = UITableViewCell()
        rowmark(mark: mark1, num: 1, r: path.row)
        rowmark(mark: mark2, num: 2, r: path.row)
        rowmark(mark: mark3, num: 3, r: path.row)
        rowmark(mark: mark4, num: 4, r: path.row)
        cell.contentView.addSubview(mark1)
        cell.contentView.addSubview(mark2)
        cell.contentView.addSubview(mark3)
        cell.contentView.addSubview(mark4)
        if(path.row == i){
            cells.append(cell)
            i += 1
            tableview.beginUpdates()
            tableview.insertRows(at: [path], with: .automatic)
            tableview.endUpdates()
            if(path.row > 6){
                tableview.scrollToRow(at: IndexPath(row: path.row - 4, section: 0), at: .middle, animated: true)
            }
        }
        else{
            cells[path.row] = cell
            tableview.reloadData()
        }
        
        tableview.reloadData()
    }
    
    //点击行改变分数
    func rowclick(path: IndexPath){
        c1 -= rec[path.row][0]
        c2 -= rec[path.row][1]
        c3 -= rec[path.row][2]
        c4 -= rec[path.row][3]
        
        po1 -= point(c: rec[path.row][0], num: 1, r: path.row)
        po2 -= point(c: rec[path.row][1], num: 2, r: path.row)
        po3 -= point(c: rec[path.row][2], num: 3, r: path.row)
        po4 -= point(c: rec[path.row][3], num: 4, r: path.row)
        
        
    }
    
    //返回行的分数和颜色
    func rowmark(mark: UILabel, num: Int, r: Int){
        var cp = 0
        if(num == 1){
            mark.text = String(point(c: cp1, num: 1, r: r)) + "[" + String(cp1) + "]"
            cp = cp1
        }
        else if(num == 2){
            mark.text = String(point(c: cp2, num: 2, r: r)) + "[" + String(cp2) + "]"
            cp = cp2
        }
        else if(num == 3){
            mark.text = String(point(c: cp3, num: 3, r: r)) + "[" + String(cp3) + "]"
            cp = cp3
        }
        else if(num == 4){
            mark.text = String(point(c: cp4, num: 4, r: r)) + "[" + String(cp4) + "]"
            cp = cp4
        }
        if(cp == 0){
            mark.textColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
        }
        else if(cp >= 1 && cp <= 7){
            mark.textColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
        }
        else if(cp >= 8 && cp <= 9){
            mark.textColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
        }
        else if(cp >= 10 && cp <= 12){
            mark.textColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
        }
        else if(cp == 13){
            mark.textColor = #colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1)
        }
    }
    
    //重置按钮
    func resetbutton(){
        let alert = UIAlertController(title: "确定清除所有记录？", message: "", preferredStyle: .alert)
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let reset = UIAlertAction(title: "重置", style: .destructive) { (action: UIAlertAction) in
            self.cp1 = 0
            self.cp2 = 0
            self.cp3 = 0
            self.cp4 = 0
            self.po1 = 0
            self.po2 = 0
            self.po3 = 0
            self.po4 = 0
            self.c1 = 0
            self.c2 = 0
            self.c3 = 0
            self.c4 = 0
            self.di1 = 0
            self.di2 = 0
            self.di3 = 0
            self.di4 = 0
            self.rec.removeAll()
            self.cells.removeAll()
            self.i = 0
            self.tableview.reloadData()
            self.writetolabel()
        }
        alert.addAction(cancel)
        alert.addAction(reset)
        self.present(alert, animated: true, completion: nil)
    }
    
    //继承picker方法
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 4
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 14
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if(row > 0){
            return String(row)
        }
        else{
            return "胜"
        }
    }
    
    //继承tableview方法
    //返回tableview有多少行
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if(tableView == self.tableview){
            return i + 1
        }
        else{
            return 7
        }
    }
    //tableview的datasource
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        var cell = UITableViewCell()
        //“新的一轮”按钮
        if(tableView == self.tableview && indexPath.row == i){
            cell.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
            cell.textLabel?.text = "新的一轮"
            cell.textLabel?.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
            cell.textLabel?.textAlignment = .center
            cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 25)
            return cell
        }
        else if (tableView == self.tableview){
            cell = cells[indexPath.row]
            return cell
        }
        else if(tableView == self.btable && indexPath.row < 3){
            cell = bcells[indexPath.row]
            return cell
        }
        else if(tableView == self.btable && indexPath.row ==  3){
            cell.frame = CGRect(x: 0, y: 0, width: 270, height: 20)
            cell.backgroundColor = UIColor.clear
            return cell
        }
        else{
            cell.frame = CGRect(x: 0, y: 0, width: 270, height: 30)
            cell.addSubview(bbtns[(indexPath.row - 4) * 3])
            cell.addSubview(bbtns[(indexPath.row - 4) * 3 + 1])
            cell.addSubview(bbtns[(indexPath.row - 4) * 3 + 2])
            cell.backgroundColor = UIColor.clear
            return cell
        }
    }
    //点击行时的事件
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableview.cellForRow(at: indexPath)
        cell?.isSelected = false
        b1.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
        b2.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
        b3.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
        b4.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
        
        if(indexPath.row == i){
            f1.append(false)
            f2.append(false)
            f3.append(false)
            f4.append(false)
            newgame(path: indexPath)
        }
        else{
            newgame(path: indexPath)
        }
    }
    //设置行高
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if(tableView == self.btable){
            return 30
        }
        else{
            return 40
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

